$(function() {
    //点击注册账号
    $('#link-reg').on('click', () => {
        $('.login-box').hide();
        $('.reg-box').show();
    });
    //点击登录
    $('#link-login').on('click', () => {
        $('.login-box').show();
        $('.reg-box').hide();
    });


    //自定义校准
    let form = layui.form;
    form.verify({
        //密码验证
        'pwd': [
            /^[\S]{6,12}$/, '密码必须6到12位,且不能出现空格'
        ],
        //注册验证
        repwd: value => {
            //value是确认密码框的内容
            let pwd = $('.reg-box [name=password]').val();
            if (pwd !== value) return '两次密码不一致'
        }
    });

    //注册功能
    $('#form_reg').on('submit', (e) => {
        // let username = $('#form_reg [name=username]').val().trim()
        // let password = $('#form_reg [name=password]').val().trim()
        // let repassword = $('#form_reg [name=repassword]').val().trim()
        // let data = { username, password, repassword }
        //layui的获取表单内容
        let data = layui.form.val('form_reg')
        e.preventDefault();
        $.post('/api/reguser', data, res => {
            if (res.status !== 0) {
                return layui.layer.msg(res.message)
            }
            layui.layer.msg('注册成功,请登录！')
                //跳转登录自动填充
            $('#link-login').trigger('click');
            $('#form_login [name=username]').val(username)
            $('#form_login [name=password]').val(password)
        })
    });

    //username:仙剑客栈  password:123123
    //登录功能
    $("#form_login").on('submit', (e) => {
        e.preventDefault();
        $.ajax({
            url: '/api/login',
            method: 'POST',
            data: $("#form_login").serialize(),
            success(res) {
                if (res.status !== 0) return layui.layer.msg('登录失败，请重新输入！')
                layui.layer.msg('登录成功！')
                    // console.log(res.token);
                    //将登陆成功的字符串保存
                localStorage.setItem('token', res.token)
                location.href = '/index.html'
            }
        })
    })
})